/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.kernel;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import fr.x9c.cadmium.util.Misc;

/**
 * This class provides methods for disassembling bytecode.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
public final class Disassembler {

    /**
     * No instance of this class.
     */
    private Disassembler() {
    } // end empty constructor

    /**
     * Disassembles an instruction.
     * @param ctxt context containing bytecode to disassemble
     *             - should not be <tt>null</tt>
     * @param pc address of instruction to disassemble
     *           - should be >= 0
     * @param out where to ouput result - should not be <tt>null</tt>
     * @return size of disassembled instruction
     */
    private static int disassemble(final Context ctxt,
                                   final int pc,
                                   final PrintWriter out) {
        assert ctxt != null : "null ctxt";
        assert pc >= 0 : "pc should be >= 0";
        assert out != null : "null out";
        final int[] code = ctxt.getCode();
        final Dispatcher disp = ctxt.getDispatcher();
        final int instr = code[pc];
        final String mnemo =
            (instr >= 0) && (instr <= Instructions.STOP)
            ? Instructions.MNEMONICS[instr]
            : "???" + instr;
        out.printf("%06d  %s", pc, mnemo);
        switch (instr) {
        case Instructions.PUSHACC:
        case Instructions.ACC:
        case Instructions.POP:
        case Instructions.ASSIGN:
        case Instructions.PUSHENVACC:
        case Instructions.ENVACC:
        case Instructions.PUSH_RETADDR:
        case Instructions.APPLY:
        case Instructions.APPTERM1:
        case Instructions.APPTERM2:
        case Instructions.APPTERM3:
        case Instructions.RETURN:
        case Instructions.GRAB:
        case Instructions.PUSHGETGLOBAL:
        case Instructions.GETGLOBAL:
        case Instructions.SETGLOBAL:
        case Instructions.PUSHATOM:
        case Instructions.ATOM:
        case Instructions.MAKEBLOCK1:
        case Instructions.MAKEBLOCK2:
        case Instructions.MAKEBLOCK3:
        case Instructions.MAKEFLOATBLOCK:
        case Instructions.GETFIELD:
        case Instructions.SETFIELD:
        case Instructions.GETFLOATFIELD:
        case Instructions.SETFLOATFIELD:
        case Instructions.BRANCH:
        case Instructions.BRANCHIF:
        case Instructions.BRANCHIFNOT:
        case Instructions.PUSHTRAP:
        case Instructions.CONSTINT:
        case Instructions.PUSHCONSTINT:
        case Instructions.OFFSETINT:
        case Instructions.OFFSETREF:
        case Instructions.OFFSETCLOSURE:
        case Instructions.PUSHOFFSETCLOSURE:
            out.printf(" %d", code[pc + 1]);
            return 2;
        case Instructions.APPTERM:
        case Instructions.CLOSURE:
        case Instructions.CLOSUREREC:
        case Instructions.PUSHGETGLOBALFIELD:
        case Instructions.GETGLOBALFIELD:
        case Instructions.MAKEBLOCK:
        case Instructions.BEQ:
        case Instructions.BNEQ:
        case Instructions.BLTINT:
        case Instructions.BLEINT:
        case Instructions.BGTINT:
        case Instructions.BGEINT:
        case Instructions.BULTINT:
        case Instructions.BUGEINT:
        case Instructions.GETPUBMET:
            out.printf(" %d, %d", code[pc + 1], code[pc + 2]);
            return 3 + (instr == Instructions.CLOSUREREC ? code[pc + 1] : 0);
        case Instructions.SWITCH:
            final long sizes = Misc.signedToUnsigned(code[pc + 1]);
            final int szTag = (int) (sizes >> 16);
            final int szInt = (int) (sizes & 0xFFFF);
            out.printf(" sz%x=%d::ntag%d nint%d", sizes, sizes, szTag, szInt);
            return 2 + szTag + szInt;
        case Instructions.C_CALLN:
            out.printf(" %d, %s", code[pc + 1], getPrimitiveName(disp, code[pc + 2]));
            return 3;
        case Instructions.C_CALL1:
        case Instructions.C_CALL2:
        case Instructions.C_CALL3:
        case Instructions.C_CALL4:
        case Instructions.C_CALL5:
            out.printf(" %s", getPrimitiveName(disp, code[pc + 1]));
            return 2;
        default:
            return 1;
        } // end switch
    } // end method 'disassemble(Context, int, PrintWriter)'

    /**
     * Disassembles an instruction and prints it on <tt>System.out</tt>. <br/>
     * No <i>end of line</i> character is printed.
     * @param ctxt context containing bytecode to disassemble
     *             - should not be <tt>null</tt>
     * @param pc address of instruction to disassemble
     *           - should be >= 0
     */
    static void disassembleInstr(final Context ctxt, final int pc) {
        disassemble(ctxt, pc, new PrintWriter(System.out));
    } // end method 'disassembleInstr(Context, int)'

    /**
     * Disassembles the whole code of a context. <br/>
     * There is one instruction per line on the output.
     * @param ctxt context whose code should be disassembled
     *             - should not be <tt>null</tt>
     * @param out where to print disassembled code
     *            - should not be <tt>null</tt>
     */
    public static void disassembleAll(final Context ctxt,
                                      final PrintStream out) {
        assert ctxt != null : "null ctxt";
        assert out != null : "null out";
        int pc = 0;
        final int len = ctxt.getCode().length;
        final PrintWriter writer = new PrintWriter(out);
        while (pc < len) {
            pc += disassemble(ctxt, pc, writer);
            writer.println();
        } // end while
        writer.flush();
    } // end method 'disassembleAll(Context, PrintStream)'

    /**
     * Disassembles an instruction.
     * @param ctxt context containing bytecode to disassemble
     *             - should not be <tt>null</tt>
     * @param pc address of instruction to disassemble
     *           - should be >= 0
     * @return a string describing the disassembled instruction
     */
    static String disassembleInstrString(final Context ctxt,
                                         final int pc) {
        final StringWriter out = new StringWriter();
        disassemble(ctxt, pc, new PrintWriter(out));
        return out.toString();
    } // end method 'disassembleInstrString(Context, int)'

    /**
     * Returns the name of a primitive.
     * @param disp dispatcher defining primitives
     * @param id primitive integer identifier
     * @return the name of the requested primitive if it exsists,
     *         <tt>"unknown primitive <i>id</i>"</tt> otherwise
     */
    private static String getPrimitiveName(final Dispatcher disp,
                                           final int id) {
        if ((id >= 0) && (id < disp.size())) {
            return disp.getName(id);
        } else {
            return "unknown primitive " + id;
        } // end if/else
    } // end method 'getPrimitiveName(Dispatcher, int)'

} // end class 'Disassembler'
